import { Config, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import * as request from 'request';
// import * as crypto from 'crypto';
const crypto = require('crypto');
import * as fs from 'fs';

/**
 * 抖音接口封装
 */
@Provide()
export class DoupiaopiaoDouyinService extends BaseService {
  @Config('module.doupiaopiao')
  doupiaopiaoConfig;

  /**
   * code2Session
   */
  code2Session(code: string, anonymous_code = '') {
    const appid = this.doupiaopiaoConfig.douyin.appid;
    const secret = this.doupiaopiaoConfig.douyin.secret;
    return new Promise((resolve, reject) => {
      let option = {
        url: 'https://developer.toutiao.com/api/apps/v2/jscode2session',
        method: 'POST',
        json: true,
        timeout: 30000,
        headers: {
          'content-type': 'application/json',
        },
        body: {
          appid,
          secret,
          code,
        },
      };
      request(option, (error, response, body) => {
        if (!error && response.statusCode == 200) {
          const { err_no, data } = body;
          if (err_no === 0) {
            resolve(data);
          } else {
            reject(body);
          }
        } else {
          reject(error); // 返回错误信息
        }
      });
    });
  }
  // 预下单接口
  ReadyOrder(goods, user) {
    const appid = this.doupiaopiaoConfig.douyin.appid;
    const requestData = {
      goods_list: [
        {
          quantity: goods.ticketNum,
          goods_image: goods.moviePoster,
          goods_title: goods.movieName,
          labels: goods.scheduleDesc,
          price: Math.round((goods.normalPayAmount / 2) * 100),
          goods_id: goods.cinemaId,
          goods_id_type: 2,
          order_valid_time: {
            valid_start_time: new Date(goods.startTime).getTime(),
            valid_end_time:
              new Date(goods.startTime).getTime() + goods.duration * 60 * 1000,
            valid_duration: new Date(goods.startTime).getTime(),
          },
        },
      ],
      pay_notify_url:
        'https://nianchu.doupiaopiao.net/app/doupiaopiao/open/orderIsComplete',
      merchant_uid: '72518571922767075840',
      total_amount: Math.round(goods.normalPayAmount * 100),
      open_id: user.dyOpenid,
      out_order_no: goods.orderNo,
      pay_expire_seconds: 300,
      order_entry_schema: {
        path: 'pages/zhifu-detail/index',
      },
    };

    const httpMethod = 'POST';
    const requestUrl = '/api/apps/trade/v2/create_order';
    const timestamp = Math.round(new Date().getTime() / 1000);
    const randomStr = `random_nonce${Math.random()}`;
    const requestBody = JSON.stringify(requestData);
    const verSion = '1';
    const signature = this.makeSign(
      httpMethod,
      requestUrl,
      timestamp,
      randomStr,
      requestBody
    );
    const mess =
      'SHA256-RSA2048 ' +
      `appid="${appid}",` +
      `nonce_str="${randomStr}",` +
      `timestamp="${timestamp}",` +
      `key_version="${verSion}",` +
      `signature="${signature}"`;
    console.log(mess, 'mess');
    return new Promise((resolve, reject) => {
      let option = {
        url: 'https://developer.toutiao.com/api/apps/trade/v2/create_order',
        method: 'POST',
        json: true,
        timeout: 30000,
        headers: {
          'Content-Type': 'application/json',
          'Byte-Authorization': mess,
        },
        body: requestData,
      };
      console.log(requestData, '打印请求');

      request(option, (error, response, body) => {
        // return body ? resolve(body) : reject(error);
        console.log(body, '打印返回的信息');

        if (!error && response.statusCode == 200) {
          const { err_no, data } = body;
          if (err_no === 0) {
            resolve(data);
          } else {
            reject(body);
          }
        } else {
          reject(error); // 返回错误信息
        }
      });
    });
  }
  makeSign(method, url, timestamp, nonce_str, requestBody) {
    const text = `${method}\n${url}\n${timestamp}\n${nonce_str}\n${requestBody}\n`;
    const privateKey = `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAwJ39J548KlAfzkkkYrOK23Icf24F7vJpJByK5imLOJ85icws
9Jr1tWs7EN4p0jCSEHPma1+cWcdxx+GReYmJvfunLPYcUf4+qmTH2SidKdFwsSDt
CZelTS0R6daPxOFp5clulpKmVALCBr9R8L8PNjcmCy7tMHJQXtK0SlDpXw1X5/Y0
yvgRs3ElF0ML20bZwB0EPBLFVcHCqkGy/3vO3lKg/dz8EHJG2LhPRWkqj88SCprF
LztJCEXQvHYf6HCjvzRDT0JI7xonkqCJNZ6WtoosuW105Yh3z7c3MZ1dxrcHH/6K
b0+KMxDYKUEzfDuHL+PKdqwwMylAAVyGW0DO1QIDAQABAoIBABMRkPZTG/G0bPGn
HAsJaz2+VkPnSH8XUIFasgWHJ1k7qh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zooLcdhblSl5rHCkU5cu86ILeaP2IOKSUQqpnohrgqmKKf+B
n74NRu0WCzmtxpQRDY8IqoA3VQIvvW06qtCxzda1bNJC0lzUM6LLIA==
-----END RSA PRIVATE KEY-----`;
    const sign = crypto.createSign('RSA-SHA256');
    sign.update(text, 'utf8');
    const privateKeyBuffer = Buffer.from(privateKey, 'utf-8');
    const signature = sign.sign(privateKeyBuffer, 'base64');
    return signature;
  }
  // makeSign(httpMethod, requestUrl, timestamp, randomStr, requestBody) {
  //   const text = `${httpMethod}\n${requestUrl}\n${timestamp}\n${randomStr}\n${requestBody}\n`;
  //   const privateKey = fs.readFileSync('/private_key.pem', 'utf-8');
  //   const sign = crypto.createSign('RSA-SHA256');
  //   sign.update(text, 'utf8');
  //   const privateKeyBuffer = Buffer.from(privateKey, 'utf-8');
  //   const signature = sign.sign(privateKeyBuffer, 'base64');
  //   return signature;
  // }
  //设置请求预下单回调地址(支付结果回调)
  settingUrlCallBack() {
    const appid = this.doupiaopiaoConfig.douyin.appid;
    const secret = this.doupiaopiaoConfig.douyin.secret;
    const requestData = {
      create_order_callback:
        'https://nianchu.doupiaopiao.net/app/doupiaopiao/open/orderIsComplete',
      refund_callback:
        'https://nianchu.doupiaopiao.net/app/doupiaopiao/open/refundIsComplete',
    };

    const httpMethod = 'POST';
    const requestUrl = '/api/apps/trade/v2/settings';
    const timestamp = Math.round(new Date().getTime() / 1000);
    const randomStr = `random_nonce${Math.random()}`;
    const requestBody = JSON.stringify(requestData);
    const verSion = '1';

    const signature = this.makeSign(
      httpMethod,
      requestUrl,
      timestamp,
      randomStr,
      requestBody
    );
    console.log(signature, '--------------');

    const mess =
      'SHA256-RSA2048 ' +
      `appid="${appid}",` +
      `nonce_str="${randomStr}",` +
      `timestamp="${timestamp}",` +
      `key_version="${verSion}",` +
      `signature="${signature}"`;
    console.log(mess, 'mess');

    // return mess;

    return new Promise((resolve, reject) => {
      let option = {
        url: 'https://developer.toutiao.com/api/apps/trade/v2/settings',
        method: 'POST',
        json: true,
        timeout: 30000,
        headers: {
          'Content-Type': 'application/json',
          'Byte-Authorization': encodeURIComponent(mess),
        },
        body: requestData,
      };
      request(option, (error, response, body) => {
        // return body ? resolve(body) : reject(error);
        console.log(body, '打印请求信息');

        if (!error && response.statusCode == 200) {
          const { err_no, data } = body;
          if (err_no === 0) {
            resolve(data);
          } else {
            reject(body);
          }
        } else {
          reject(error); // 返回错误信息
        }
      });
    });
  }
  //开发者发起退款
  RefundOrder(bodys) {
    const appid = this.doupiaopiaoConfig.douyin.appid;
    const secret = this.doupiaopiaoConfig.douyin.secret;
    const httpMethod = 'POST';
    const requestUrl = '/api/apps/trade/v2/create_refund';
    const timestamp = Math.round(new Date().getTime() / 1000);
    const randomStr = `random_nonce${Math.random()}`;
    const requestBody = JSON.stringify(bodys);
    const verSion = '1';
    const signature = this.makeSign(
      httpMethod,
      requestUrl,
      timestamp,
      randomStr,
      requestBody
    );
    console.log(signature, '--------------');

    const mess =
      'SHA256-RSA2048 ' +
      `appid="${appid}",` +
      `nonce_str="${randomStr}",` +
      `timestamp="${timestamp}",` +
      `key_version="${verSion}",` +
      `signature="${signature}"`;
    console.log(mess, 'mess');

    // return mess;

    return new Promise((resolve, reject) => {
      let option = {
        url: 'https://developer.toutiao.com/api/apps/trade/v2/create_refund',
        method: 'POST',
        json: true,
        timeout: 30000,
        headers: {
          'Content-Type': 'application/json',
          'Byte-Authorization': mess,
        },
        body: bodys,
      };
      request(option, (error, response, body) => {
        // return body ? resolve(body) : reject(error);
        console.log(body, '打印请求信息');

        if (!error && response.statusCode == 200) {
          const { err_no, data } = body;
          if (err_no === 0) {
            resolve(data);
          } else {
            reject(body);
          }
        } else {
          reject(error); // 返回错误信息
        }
      });
    });
  }
}
